package com.useeinfo.oa.modules.base.dao;

import com.alibaba.fastjson.JSONArray;
import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.PersonnnelOrganization;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date: 2018/12/3 17:05
 * @Description:
 */
@Repository("personnnelOrganizationDao")
public class PersonnnelOrganizationDao implements CrudDao<PersonnnelOrganization> {

    private final static Logger logger = LoggerFactory.getLogger(PersonnnelOrganizationDao.class);

    @PersistenceContext
    private EntityManager entityManager;


    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {
        Map<String, Object> conditionHash = new HashMap<>();
        conditionHash.put("s.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        for(String key:queryHash.keySet()){
            String value = queryHash.get(key);
            switch (key){
                case "enterpriseId":
                    conditionHash.put("s.organization.enterprise.id = ?{paramIndex}", StringConverters.null2Long(value));
                    continue;
                case "personnelId":
                    conditionHash.put("s.personnel.id = ?{paramIndex}", StringConverters.null2Long(value));
                    continue;
            }
        }

        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {

        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(s) from PersonnnelOrganization s ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<PersonnnelOrganization> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select s from PersonnnelOrganization s ", "order by s.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<PersonnnelOrganization> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, PersonnnelOrganization.class);
        return queryParam.findPageList(typedQuery);
    }

    @Override
    public PersonnnelOrganization findModel(Long userId) {
        return entityManager.find(PersonnnelOrganization.class, userId);
    }

    @Override
    public Integer add(PersonnnelOrganization personnnelOrganization) {
        personnnelOrganization.setCreateDate(new Date());
        entityManager.persist(personnnelOrganization);
        logger.info("PersonnnelOrganizationDaoImpl添加personnnelOrganization成功！");
        return 1;
    }

    @Override
    public Integer update(PersonnnelOrganization personnnelOrganization) {
        personnnelOrganization.setUpdateDate(new Date());
        entityManager.merge(personnnelOrganization);
        return 1;
    }

    @Override
    public Integer delete(Long personnnelOrganizationId) {
        PersonnnelOrganization personnnelOrganization = entityManager.find(PersonnnelOrganization.class, personnnelOrganizationId);
        entityManager.remove(personnnelOrganization);
        return 1;
    }

    @Override
    public Integer deleteLogic(PersonnnelOrganization model) {
        model.setDeleteStatus(true);
        return 1;
    }

    public List<PersonnnelOrganization> hqlExcute(String hql) {
        return entityManager.createQuery(hql,PersonnnelOrganization.class).getResultList();
    }

    public List<Object[]> orderInfo(Integer pageIndex,Integer pageSize,List<Long> ids){
        String sql = "SELECT * FROM ((SELECT 'REPAIR','维修模块',a.id,a.create_date,a.report_code,e.user_name,a.receive_date, " +
                "a.presence_time,a.repair_finish_time,a.report_content,b.color,c.area_name,a.major_name,a.report_address " +
                "FROM repair_order a " +
                "LEFT JOIN repair_level b " +
                "ON a.report_level = b.id " +
                "LEFT JOIN AREA c " +
                "ON a.area_id = c.id " +
                "LEFT JOIN SYSTEM_USER e " +
                "ON e.id = a.report_user_id WHERE 1 = 1 ";
         if(CollectionUtils.isNotEmpty(ids)){
             sql += "AND a.enterprise_id in (" + StringUtils.strip(ids.toString(),"[]") +") ";
         }
         sql += "AND a.source in ('CUSTOMER_REPORT') " +
                 "AND a.repair_order_type in ('COMMON_ORDER','FACILITY_ORDER','400_ORDER')";
         sql += ") ";
         sql += "UNION ALL " +
                "( " +
                "SELECT 'MAINTAIN','维保模块',a.id,a.create_date,a.order_code,c.user_name,a.receive_date,a.presence_time,a.finish_time,'',b.property_code,'','','' " +
                "FROM maintain_order a  " +
                "LEFT JOIN dict_info b " +
                "ON a.degree = b.id " +
                "LEFT JOIN SYSTEM_USER c " +
                "ON a.create_user_id = b.id WHERE 1 = 1 ";
        if(CollectionUtils.isNotEmpty(ids)){
            sql += "AND a.enterprise_id in (" + StringUtils.strip(ids.toString(),"[]") +") ";
        }
        sql += ") ";
        sql += "UNION ALL " +
                "( " +
                "SELECT 'INSPECTION','巡检模块',a.id,a.create_date,a.order_code,c.user_name,a.receive_date,a.presence_time,a.finish_time,'',b.property_code,'','','' FROM inspection_order a " +
                "LEFT JOIN dict_info b " +
                "ON a.degree = b.id " +
                "LEFT JOIN SYSTEM_USER c " +
                "ON a.create_user_id = c.id WHERE 1 = 1 ";
        if(CollectionUtils.isNotEmpty(ids)){
            sql += "AND a.enterprise_id in (" + StringUtils.strip(ids.toString(),"[]") +") ";
        }
        sql += ") ";
        sql +=  ") a ORDER BY a.create_date DESC " +
                " LIMIT  " + pageIndex + "," + pageSize;
        return entityManager.createNativeQuery(sql).getResultList();
    }

    public Object orderInfoSize(List<Long> ids){
        String sql = "SELECT count(*) FROM ((SELECT 'REPAIR','维修模块',a.id,a.create_date,a.report_code,e.user_name,a.receive_date, " +
                "a.presence_time,a.repair_finish_time,a.report_content,b.color,c.area_name,a.major_name,a.report_address " +
                "FROM repair_order a " +
                "LEFT JOIN repair_level b " +
                "ON a.report_level = b.id " +
                "LEFT JOIN AREA c " +
                "ON a.area_id = c.id " +
                "LEFT JOIN SYSTEM_USER e " +
                "ON e.id = a.report_user_id WHERE 1 = 1 ";
        if(CollectionUtils.isNotEmpty(ids)){
            sql += "AND a.enterprise_id in (" + StringUtils.strip(ids.toString(),"[]") +") ";
        }
        sql += "AND a.source in ('CUSTOMER_REPORT') " +
                "AND a.repair_order_type in ('COMMON_ORDER','FACILITY_ORDER','400_ORDER')";
        sql += ") ";
        sql += "UNION ALL " +
                "( " +
                "SELECT 'MAINTAIN','维保模块',a.id,a.create_date,a.order_code,c.user_name,a.receive_date,a.presence_time,a.finish_time,'',b.property_code,'','','' " +
                "FROM maintain_order a  " +
                "LEFT JOIN dict_info b " +
                "ON a.degree = b.id " +
                "LEFT JOIN SYSTEM_USER c " +
                "ON a.create_user_id = b.id WHERE 1 = 1 ";
        if(CollectionUtils.isNotEmpty(ids)){
            sql += "AND a.enterprise_id in (" + StringUtils.strip(ids.toString(),"[]") +") ";
        }
        sql += ") ";
        sql += "UNION ALL " +
                "( " +
                "SELECT 'INSPECTION','巡检模块',a.id,a.create_date,a.order_code,c.user_name,a.receive_date,a.presence_time,a.finish_time,'',b.property_code,'','','' FROM inspection_order a " +
                "LEFT JOIN dict_info b " +
                "ON a.degree = b.id " +
                "LEFT JOIN SYSTEM_USER c " +
                "ON a.create_user_id = c.id WHERE 1 = 1 ";
        if(CollectionUtils.isNotEmpty(ids)){
            sql += "AND a.enterprise_id in (" + StringUtils.strip(ids.toString(),"[]") +") ";
        }
        sql += ") ";
        sql +=  ") a ORDER BY a.create_date DESC ";
        return entityManager.createNativeQuery(sql).getSingleResult();
    }


    public int getOrderNumByDate(String dateTime,String type,String enterpriseId){
        int num = 0;
        String sql = "";
        if("MAINTAIN".equals(type)){
            sql = "SELECT COUNT(*) FROM maintain_order WHERE 1 = 1 " +
                    "AND DATE_FORMAT(create_date,'%Y-%m-%d')  = '" + dateTime +"' AND delete_status = 0\n";
            if(StringUtils.isNotBlank(enterpriseId)){
                sql += "AND enterprise_id = " + enterpriseId + " ";
            }
        }else if("REPAIR".equals(type)){
            sql = "SELECT COUNT(*) FROM repair_order WHERE 1 = 1 " +
                    "AND DATE_FORMAT(create_date,'%Y-%m-%d')  = '" + dateTime +"' AND delete_status = 0\n" +
                    "AND source = 'CUSTOMER_REPORT'\n" +
                    "AND repair_order_type IN ('COMMON_ORDER','FACILITY_ORDER','_400_ORDER') ";
            if(StringUtils.isNotBlank(enterpriseId)){
                sql += "AND enterprise_id = " + enterpriseId + " ";
            }
        }else if("INSPECTION".equals(type)){
            sql = "SELECT COUNT(*) FROM inspection_order WHERE 1 = 1 " +
                    "AND DATE_FORMAT(create_date,'%Y-%m-%d')  = '" + dateTime +"' AND delete_status = 0\n";
            if(StringUtils.isNotBlank(enterpriseId)){
                sql += "AND enterprise_id = " + enterpriseId + " ";
            }
        }else{
            return 0;
        }
        Object result = entityManager.createNativeQuery(sql).getSingleResult();
        if(result == null) {
            return num;
        }else {
            return StringConverters.null2Int(result);
        }
    }
}
